<!--  注册子组件-->
<template>
  <div>
    <el-dialog :visible.sync="dialogVisible" width="600px" center="">
      <span class="el-dialog__title" slot="title">注 册</span>
      <el-form
        :model="form"
        label-position="left"
        ref="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :data="uploadData"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="16">
            <el-form-item label="图形码" prop="code">
              <el-input v-model="form.code"></el-input>
            </el-form-item>
          </el-col>
          <el-col style="margin-left:10px" :span="7">
            <img
              :src="changeCodeUrl"
              style="width:100%;height:40px"
              @click="changeUrl"
              alt=""
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="验证码" prop="rcode">
              <el-input
                placeholder="请输入验证码"
                v-model="form.rcode"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col style="margin-left:10px" :span="7">
            <el-button size="default" @click="getRcode"
              >获取用户验证码</el-button
            >
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="register"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { delete } from 'vue/types/umd'
export default {
  data () {
    return {
      changeCodeUrl: `${process.env.VUE_APP_BASEURL}/captcha?type=sendsms`,
      dialogVisible: false,
      imageUrl: '', //上传后的地址
      uploadUrl: `${process.env.VUE_APP_BASEURL}/uploads`, //上传地址
      uploadData: {
        //上传参数
        image: null
      },
      form: {
        username: '', //昵称
        phone: '', //手机号
        email: '', //邮箱
        avatar: '', //头像地址
        password: '', //密码
        code: '', //图形码
        rcode: '' //验证码
      },
      rules: {
        avatar: [{ required: true, message: '请输入头像', trigger: 'change' }],
        username: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('邮箱不能为空'))
              }
              //eslint禁用
              /* eslint-disable */
              const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
              //eslint开启
              /* eslint-disable no-new */
              if (!reg.test(value)) {
                return callback(new Error('邮箱不合法'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('手机号不能为空'))
              }
              const reg = /^1[3-9][0-9]{9}$/
              if (!reg.test(value)) {
                return callback(new Error('手机号不合法'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码为6-16位', trigger: 'blur' }
        ],
        code: [{ required: true, message: '请输入图形码', trigger: 'blur' }],
        rcode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    changeUrl () {
      this.changeCodeUrl = `${
        process.env.VUE_APP_BASEURL
      }/captcha?type=sendsms&t=${new Date() - 0}`
    },
    async getRcode () {
      let isOK = 0
      this.$refs.form.validateField(['phone'], errorMessage => {
        // console.log(errorMessage);
        if (!errorMessage) {
          isOK++
        }
      })
      this.$refs.form.validateField(['code'], errorMessage => {
        if (!errorMessage) {
          isOK++
        }
      })
      if (isOK == 2) {
        // this.$axios.post('/sendsms',{
        //   phone:this.form.phone,
        //   code:this.form.code
        // }).then(res=>{
        //   console.log(res);
        // })
        const res = await this.$axios.post('/sendsms', {
          code: this.form.code,
          phone: this.form.phone
        })
        // console.log(res)
        if (res.code == 200) {
          this.form.rcode = res.data.captcha
        } else {
          this.$message.error(res.message)
          this.changeUrl()
        }
      }

      // if (this.form.phone.trim().length>0 && this.form.code.trim().length > 0) {
      //   console.log('ok');
      // }
    },
    // 上传成功
    handleAvatarSuccess (res, file) {
      // console.log(res);
     if (res.code===200) {
       
       this.imageUrl = URL.createObjectURL(file.raw);
       this.form.avatar = res.data.file_path;
     }else {
       this.$message.error(res.message)
     }
    },
    // 上传失败
    handleAvatarError (err) {
      console.log(err);
      this.$message.error('上传失败');
    },
    // 上传之前
    beforeAvatarUpload (file) {
      const isimage =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isimage) {
        this.$message.error('上传头像图片只能是 JPG/png/gif 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      this.uploadData.image = file
      return isimage && isLt2M
    },
    //注册
    register(){
      //校验全部
      this.$refs.form.validate( async valid=>{
        if(!valid) return
        delete this.form.code;

     const res = await this.$axios.post('/register',this.form)
     console.log(res);
     if (res.code === 200) {
       this.$message.success('注册成功')
        this.dialogVisible = false
     } else {
       console.log('111');
       this.$message.error(res.message)
       this.changeUrl()
     }
    
      })
    }
  }
}
</script>

<style lang="less">
.el-dialog__header {
  background: linear-gradient(270deg, #01c6fa, #1493fa);
  text-align: center;
}
.el-dialog__title {
  color: #fff;
}
.el-dialog__close {
  color: #fff !important;
}
.avatar-uploader {
  display: flex;
  justify-content: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
